package com.zzj.ecology.framework.configs.security.handler;

import com.alibaba.fastjson.JSON;
import com.zzj.ecology.common.constant.Constant;
import com.zzj.ecology.common.enums.LoginResultEnum;
import com.zzj.ecology.common.utils.*;
import com.zzj.ecology.framework.manager.AsyncManager;
import com.zzj.ecology.framework.manager.async.AsyncTaskFactory;
import com.zzj.ecology.framework.utils.SecurityUtils;
import com.zzj.ecology.system.bean.minitor.SysUserOnline;
import com.zzj.ecology.system.bean.system.SysUser;
import com.zzj.ecology.system.dto.HttpResult;
import com.zzj.ecology.system.service.system.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @ClassName CustomizeAuthenticationSuccessHandler
 * @Description 登录成功的处理逻辑
 * @Author zhijun zeng at 2020/2/28
 * @Version 1.0
 **/
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AsyncManager asyncManager;
    @Autowired
    private AsyncTaskFactory asyncTaskFactory;
    @Autowired
    private SysUserService sysUserService;

    private static final String AUTHRORIZED = "AUTHORIZED";


    @Override
    public void onAuthenticationSuccess(HttpServletRequest req,
                                        HttpServletResponse resp,
                                        Authentication auth) throws IOException, ServletException {

        //获取 认证 成功的 用户
        String username = SecurityUtils.getUsername();
        //User user = (User) SecurityUtils.getPrincipalObject();
        User principal = (User) SecurityUtils.getPrincipalObject();
        SysUser byUsername = sysUserService.findByUsername(username);
        req.setAttribute(AUTHRORIZED, byUsername);
        HttpResult result = new HttpResult(LoginResultEnum.USER_LOGIN_SUCCESS).add(HttpResult.DATA_TAG, principal);
        result.add(JWTUtils.TOKEN_KEY, JWTUtils.buildToken(byUsername.getUserId(), username));

        logger.info("{} -----------> JsessionId: {}", this.getClass().getName(),req.getSession().getId());

        // 登录成功
        //All javascript context is unloaded and lost when the browser navigates to another page.
        //使用 window.location.href 从登录页面跳转到INDEX页面，sessionId 不一致
        //logger.info("{}.sessionCreated() --> 创建Session: {}, 在线人数：{}",this.getClass().getName(), session.getId());

        // 往sys_user_online插入值
        Date loginTime = new Date();
        //修改 登录时间
        sysUserService.updateLoginDateAndLoginIpByUsername(new SysUser(username, IpUtils.getIPAddress(req), loginTime));
        // 写到Session表中
        SysUserOnline sysUserOnline = new SysUserOnline();
        sysUserOnline.setSessionId(req.getRequestedSessionId());
        sysUserOnline.setDeptName("");
        sysUserOnline.setLoginName(username);
        sysUserOnline.setIpaddr(IpUtils.getIPAddress(req));
        sysUserOnline.setStartTimestamp(loginTime);
        sysUserOnline.setLoginLocation(AddressUtils.getRealAddressByIP(sysUserOnline.getIpaddr()));

        asyncManager.execute(asyncTaskFactory.recordOnline(sysUserOnline));
        //写日志
        asyncManager.execute(asyncTaskFactory.recordLoginInfor(username,
                Constant.LOGIN_SUCCESS, loginTime, MessageUtils.message("user.login.success")));

        //resp.setContentType("text/json;charset=utf-8");
        //resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);//
        //resp.getWriter().write(JSON.toJSONString(result));
        ServletUtils.renderString(resp, JSON.toJSONString(result));
    }
}
